package com.wbr.file.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wbr.file.VO.ImageVO;
import com.wbr.file.utils.JsonResult;
import com.wbr.file.utils.ZipUtils;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;

import sun.misc.BASE64Decoder;


@Controller
@RequestMapping("/upload")
@Api(value="restful",description="upload")
public class ImageUploadController {

	@RequestMapping("/uploadImage")
	public String uploadImagePage() {
		return "/upload/uploadImage";
	}

	@RequestMapping(value = "/uploadPoster")
	@ResponseBody
	@ApiOperation("上传头像")
	public JsonResult uploadPoster(HttpServletRequest request, @RequestBody ImageVO vo) throws Exception {
		JsonResult result = new JsonResult();
		System.out.println("开始上传照片");
		String customerId = vo.getAccountId();
		String imageStr = vo.getImageStr();
		System.out.println("图片字符串：" + imageStr);
		System.out.println("用户帐号：" + customerId);
		String ret_fileName = null;// 返回给前端已修改的图片名称
		// 临时文件路径
		String dirTemp = "\\employeeTempImage";

		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			result.setMsg("上传图片失败");
			result.setStatus(404);
			return result;
		}

		// 创建文件存放路径
		String realPath = request.getSession().getServletContext().getRealPath("Eimg");
		System.out.println(realPath);
		String tempPath = request.getServletContext().getRealPath("/") + dirTemp;
		File file_normer = new File(realPath);
		if (!file_normer.exists()) {
			file_normer.mkdirs();
		}

		// 用于设置图片过大，存入临时文件
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设定使用内存超过5M时，将产生临时文件并存储于临时目录中。
		factory.setSizeThreshold(20 * 1024 * 1024);
		// 设定存储临时文件的目录。
		factory.setRepository(new File(tempPath));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		if (imageStr == null) { // 图像数据为空
			result.setMsg("图像数据为空");
			result.setStatus(400);
			return result;
		}
		imageStr = imageStr.replaceAll("data:image/jpeg;base64,", "");
		try {
			// Base64解码
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] b = decoder.decodeBuffer(imageStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					// 调整异常数据
					b[i] += 256;
				}
			}

			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");

			// 生成jpeg图片
			ret_fileName = new String((format.format(new Date()) + ".jpg").getBytes("gb2312"), "ISO-8859-1");
			File file = new File(realPath + "/" + customerId + "_" + ret_fileName);
			System.out.println(file.getAbsolutePath());
			OutputStream out = new FileOutputStream(file);
			out.write(b);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		String image_url = request.getSession().getServletContext().getContextPath() + "/" + "Eimg/" + customerId + "_"
				+ ret_fileName;
		// 将已修改的图片url对应的id返回前端
		result.setMsg("图片上传成功");
		result.setStatus(200);
		result.setData(image_url);
		return result;
	}
}